<?php

namespace API\App\Event;

use API\ORG\Xml;
use Hx\Error;
use Hx\Request;
use Hx\Router;
use Hx\App;

class Response {

    public static function format($data) {
        if (!$data) {
            return;
        }
        if (Router::getExt() === 'xml') {
            Xml::setCDATA('desc', 'content', 'avatar');
            \Hx\Response::setHeader('Content-Type', 'text/xml;charset=UTF-8');
            \Hx\Response::setResBody(Xml::build($data));
        } else {
            \Hx\Response::setHeader('Content-Type', 'application/json;charset=UTF-8');
            \Hx\Response::setResBody(json_encode($data));
        }
        \Hx\Response::sendResponse();
    }

    public static function token() {
        $token = Request::getHttp('X_Token');
        $user = Request::getHttp('X_User');
        $app = strtoupper(Request::getHttp('X_App'));
        if (!$user || !$token || !$app) {
            \Hx\Response::setStatus(401);
            self::format(array('error' => \Hx\Response::getStatusText(401)));
            exit;
        }
        $res = App::Model('User->checkToken', array($user, $token, $app));
        if ($res !== true) {
            \Hx\Response::setStatus(401);
            self::format(array('error' => \Hx\Response::getStatusText(401)));
            exit;
        }
    }

    public static function error(Error $error) {
        $status = $error->getStatusCode();
        \Hx\Response::setStatus($status);
        self::format(array(
            'error' => \Hx\Response::getStatusText($status)
            //'msg'=>$error->getMessage()
        ));
        exit;
    }
}